# -*- coding: utf-8 -*-
# @Time    : 2021/12/16 10:13
# @Email   : 849080458@qq.com
# @Author  : zgh
# @FileName: day02_ajax.py
# @Software: PyCharm
import os.path
import time

from flask import Flask, request, render_template, send_from_directory
from flask.views import View
from werkzeug.utils import secure_filename

app = Flask(__name__)


# app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024   # 可设置上传文件大小


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('../class9_flask基本结构/templates/index.html')
    elif request.method == 'POST':
        a = request
        print(request.json)
        print(request.form)
        print(request.content_type)
        print(request.environ)
        return '成功'


# 文件类型的大小和类型限制
def allowed_format(filename):
    format_list = ['jpg', 'png']
    format_file = filename.split('.')[1]
    if format_file in format_list:
        return True
    return False


@app.route('/upload', methods=['GET', 'POST'])
def upload():
    # TODO: 文件类型的大小和类型限制
    file = request.files.get('pic')
    if file is None:
        return render_template('../class9_flask基本结构/templates/index.html')
    if allowed_format(file.filename):
        # TODO:BUG,上传文件一定要注意处理空格方法》》》》secure_filename 时间戳
        file.save(secure_filename(file.filename))
        return 'save success'
    return 'error'


@app.route('/upload/<filename>')
def get_upload(filename):
    # 通过获取路径或指定路径，可直接返回相关文件和图片
    return send_from_directory(os.getcwd(), filename)


if __name__ == '__main__':
    app.run(debug=True)
